package com.liangtian.mdm.dm.group.service.impl;

import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.dm.group.dao.AttrGroupDao;
import com.liangtian.mdm.dm.group.model.AttrGroup;
import com.liangtian.mdm.dm.group.service.AttrGroupService;
import com.liangtian.mdm.dm.listener.CacheUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AttrGroupServiceImpl implements AttrGroupService {

    private static Logger log = LoggerFactory.getLogger(AttrGroupServiceImpl.class);

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public List<AttrGroup> queryAttributeList(String modelId) {
        return attrGroupDao.queryAttributeList(modelId);
    }

    @Override
    public List<AttrGroup> queryGroupByModelId(String modelId) {
        return attrGroupDao.queryGroupByModelId(modelId);
    }

    @Override
    public boolean saveOrUpdateRelation(List<AttrGroup> result) {

        boolean isSuccess = true;
        try {
            //获取属性组
            List<AttrGroup> groups = new ArrayList<AttrGroup>();
            for (AttrGroup ag : result) {
                //无组属性信息还原，即默认属性组
                if (ag.getGroupId() == 0) {
                    ag.setGroupId(null);
                    ag.setGroupName(null);
                    ag.setIsDefaultView(1);
                }
                //提取属性组
                else if (!groups.contains(ag)) {
                    groups.add(ag);
                }
            }
            //result.removeAll(groups);
            //log.info("------groups-----");
            //log.info(JSON.toJSONString(groups));

            //更新
            List<AttrGroup> update = new ArrayList<>();
            //插入
            List<AttrGroup> insert = new ArrayList<>();
            //删除
            Set<String> ids = new HashSet<>();
            for (AttrGroup g : groups) {
                Long g_id = g.getGroupId();
                //if(g_id!=null){
                if (g_id < 0) {
                    //g.setGroupId(null);
                    insert.add(g);
                } else {
                    update.add(g);
                    ids.add(String.valueOf(g_id));
                }
                //}
            }

            String modelId = result.get(0).getModelId() + "";
            //删除 am_attr_group  一定要先删除，否则要排除新增属性组
            Map<String, Object> param = new HashMap<>();
            param.put("modelId", modelId);
            if (!ids.isEmpty())
                param.put("ids", ids);
            //log.info("------batchDelete-----");
            //log.info(JSON.toJSONString(param));
            attrGroupDao.batchDelete(param);

            //log.info("------batchUpdate-----");
            //log.info(JSON.toJSONString(update));
            //更新 am_attr_group
            if (update.size() > 0)
                attrGroupDao.batchUpdate(update);

            //log.info("------batchInsert-----");
            //log.info(JSON.toJSONString(insert));
            //插入 am_attr_group
            Map<String, String> keys = new HashMap<>();
            if (insert.size() > 0) {
                //获取属性组ID
                String[] seqIds = jdbcDao.getIdsBySeq("am_attr_group_seq", insert.size());
                for (int i = 0; i < insert.size(); i++) {
                    keys.put(insert.get(i).getGroupId().toString(), seqIds[i]);
                    insert.get(i).setGroupId(Long.valueOf(seqIds[i]));
                }
                //log.info(JSON.toJSONString(insert));
                //插入
                attrGroupDao.batchInsert(insert);
                //int ret = attrGroupDao.insertOne(g);
            }

            //log.info(JSON.toJSONString(keys));
            if (insert.size() > 0) {
                //result.addAll(insert);
                // 反写新增属性ID
                for (AttrGroup ag : result) {
                    if (ag.getGroupId() != null && ag.getGroupId() < 0) {
                        ag.setGroupId(Long.valueOf(keys.get(ag.getGroupId().toString())));
                    }
                }
            }
            //log.info("------batchUpdateRelation-----");
            //log.info(JSON.toJSONString(result));
            //更新 am_attr_config
            attrGroupDao.batchUpdateRelation(result);
            //当前属性组的变化，造成缓存的脏数据，移除缓存
            cacheUtil.removeAttrConfig(modelId);
        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
        }
        return isSuccess;
    }

}
